#!/usr/bin/perl -w
use strict;
use DBI;
use Statistics::Descriptive;

# Jason Weirather
# this will take a human bed file and convert it into
# a more generic format for other species.  it stores
# info about it in the database.  You will be able to
# it will allow you to track the original source of the
# feature if it is used.

# this will load a bed file into the database so it will be usable by other programs.
#### we need to bring in quite a bit of information to properly label any thing we load
#warning!  it uses temp files.  multiple instances will be crippled for now. 
#this depends on liftOver from UCSC.  It needs to be in the same directory as this
#and your peak files.

if(scalar(@ARGV) < 5) { die "not enough arguments.\n"; }

my $original_source = shift @ARGV;
my $original_species = shift @ARGV;
my $species = shift @ARGV;
my $celltype = shift @ARGV;
my $feature = shift @ARGV;



#### generic file information
my $chromosome_field = 0;
my $start_field = 1;
my $finish_field = 2;
my $score_field = 3;


#### experiment specific information
#my $species = 'danrer4';
my $feature_name = $feature;
my $cell_type = $celltype;
my $note = 'combined from ENCODE Histone Modifications by Broad Institute ChIP-seq';
my $replicate_number = 1;
my $conversion = 'no'; # if yes, it is a conversion from one species to another.

#### conversion specific information

#### do the conversion ### this is depreciated since local liftover does not work.
open(INF,"$original_source");
chomp(my @lines = <INF>);
close INF;
open(OF,">/tmp/before_liftover.bed");
open(TF,">/tmp/translate_bed.txt"); #this will be used to put it back together.
#### experiment specific information
print TF "$species\n";
print TF "$original_source\n";
print TF "$feature_name\n";
print TF "$cell_type\n";
print TF "$note\n";
print TF "$replicate_number\n";
print TF "$conversion\n";  # if yes, it is a conversion from one species to another.
print TF "$original_species\n";
#foreach my $line (@lines) {
for(my $i=0; $i < scalar(@lines); $i++) {
  my @fields = split(/\t/,$lines[$i]);
  my $index = $i+1;
  print OF "$fields[$chromosome_field]\t$fields[$start_field]\t$fields[$finish_field]\t$index\n";
  print TF "$index\t$fields[$chromosome_field]\t$fields[$start_field]\t$fields[$finish_field]\t$fields[$score_field]\n";
}
close OF;
close TF;

